//
//  SinaHomeController.swift
//  SinaWeibo
//
//  Created by 王朝阳 on 2016/10/22.
//  Copyright © 2016年 wangzhaoyang. All rights reserved.
//

import UIKit
import YYModel
private let statusCellIdentifier = "statusCellIdentifier"

class SinaHomeController: SinaVisitorViewController {
    
    //viewModel 对象
    let statuListViewModel = SinaStatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //        view.backgroundColor = UIColor.lightGray
        //判断用户是否登录
        if !isLogin {
            visitorView?.setupVisitorViewInfo(imageName: nil, title: nil)
            return
        }
        setupUI()
        getStatusData()
        
        //添加 tipLabel
        if let nav = self.navigationController {
            
            //表示导航控制器存在
            nav.view.insertSubview(tipLabel, belowSubview: nav.navigationBar)
            //获取最大 Y 轴
            tipLabel.frame = CGRect(x: 0, y: nav.navigationBar.frame.maxY - 35, width: nav.navigationBar.frame.width, height: 35)
        }
    }
    
    //MARK: -点击事件
    @objc private func scanClick() {
        print("扫一扫")
    }
    @objc private func rightClick() {
        print("跳到下一页")
        let tempVC = SinaTempController()
        
        //跳转之前,设置跳转后隐藏标签栏
        tempVC.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(tempVC, animated: true)
    }
    //MARK: - 创建视图
    private func setupUI() {
        
        setupNav()
        setupTableViewInfo()
    }
    
    //MARK: - 设置 tableView 的相关信息
    private func setupTableViewInfo() {
        //设置数据源
        tableView.dataSource = self
        tableView.delegate = self
        //注册 cell
        tableView.register(SinaHomeCell.self, forCellReuseIdentifier: statusCellIdentifier)
        //自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        //设置预估行高,越接近真实行高越好
        tableView.estimatedRowHeight = 200
        //tableView 的显示样式
        tableView.separatorStyle = .none
        
        //设置 footView
        tableView.tableFooterView = bottomView
        //添加系统下拉刷新控件
        tableView.addSubview(refreshControl)
        refreshControl.addTarget(self, action: #selector(getStatusData), for: UIControlEvents.valueChanged)
    }
    //MARK: -设置导航条
    func setupNav() {
        
        //创建按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(setHighlightedImgName: "navigationbar_pop", target: self, action: #selector(scanClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(setHighlightedImgName: "navigationbar_friendsearch", target: self, action: #selector(rightClick))
    }
    //MARK: - tipLabel 动画
    fileprivate func startTipAnimation(message: String) {
        
        if tipLabel.isHidden == false {
            //  表示正在执行动画
            return
        }
        
        tipLabel.isHidden = false
        tipLabel.text = message
        
        UIView.animate(withDuration: 1, animations: {
            self.tipLabel.transform = CGAffineTransform(translationX: 0, y: self.tipLabel.frame.height)
            
            
        }) { (_) in
            
            UIView.animate(withDuration: 1, animations: {
                self.tipLabel.transform = CGAffineTransform.identity
            }, completion: { (_) in
                self.tipLabel.isHidden = true
            })
            
        }
        
    }
    
    //MARK: - 懒加载刷新控件
    fileprivate lazy var bottomView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
        //设置颜色
        view.color = UIColor.green
        return view
    }()
    
    //系统的下拉刷新控件
    fileprivate lazy var refreshControl: SinaRefreshControl = SinaRefreshControl()
    //tipLabel
    fileprivate lazy var tipLabel: UILabel = {
        let label = UILabel(text: "没有加载到最新微博数据", fontSize: 11, textColor: UIColor.white)
        label.backgroundColor = SinaRandomColor()
        label.textAlignment = .center
        //默认状态隐藏
        label.isHidden = true
        return label
    }()
}
//MARK: - 请求数据
extension SinaHomeController{
    //请求数据
    func getStatusData() {
        //委托 statuListViewModel 请求数据
        print("需要下拉刷新")
        
        statuListViewModel.getHomeData(isPullUp: bottomView.isAnimating) { (isSuccess, message) in
            
            if !self.bottomView.isAnimating {
                self.startTipAnimation(message: message)
            }
            if !isSuccess {
                print("请求失败")
                return
            }
            //刷新 UI
            self.tableView.reloadData()
        }
        //停止动画
        self.endRefreshing()
        
    }
    
    //停止下拉和上拉的动画
    func endRefreshing() {
        // 停止动画
        self.bottomView.stopAnimating()
        // 下拉刷新也要停止
        self.refreshControl.endRefreshing()
    }
    
}
//MARK: - tableView 数据源方法
extension SinaHomeController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuListViewModel.dataArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: statusCellIdentifier, for: indexPath) as! SinaHomeCell
        //将 cell 的选中模式设置成 none
        cell.selectionStyle = .none
        
        //给 cell 赋值
        cell.statusViewModel = statuListViewModel.dataArray[indexPath.row]
        
        return cell
    }
    
    //将要显示的 cell
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        //如果 indexPath.row == 19 -> count - 1 就代表显示的是最后一个 cell
        if indexPath.row == statuListViewModel.dataArray.count - 1 && !bottomView.isAnimating {
            //开启动画
            bottomView.startAnimating()
            //马上请求数据
            getStatusData()
        }
    }
}
